<template>
  <div class="manage">
    <el-dialog
        :title="operateType === 'add' ? '新增用户' : '更新用户'"
        :visible.sync="isShow"
    >
      <common-form
          :formLabel="opertateFormLabel"
          :form="operateForm"
          :inline="true"
          ref="form"
      >
      </common-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
    <div class="manage-header">
      <el-button
          type="primary"
          @click="addUser"
          :style="{ height: '40px', 'margin-top': '-20px' }"
      >+新增</el-button
      >
      <common-form
          :formLabel="formLabel2"
          :form="searchFrom1"
          :inline="true"
          ref="form"
      >
        <!-- 改3 -->
        <!-- <el-button type="primary" @click="getDelete">删除状态搜索</el-button> -->
      </common-form>
      <common-form
          :formLabel="formLabel"
          :form="searchFrom2"
          :inline="true"
          ref="form"
      >
        <el-button type="primary" @click="getData">用户名搜索</el-button>
      </common-form>
      <common-form
          :formLabel="formLabel"
          :form="searchFrom3"
          :inline="true"
          ref="form"
      >
        <el-button type="primary" @click="getList">ID查找</el-button>
      </common-form>
    </div>
    <div class="common-table">
      <!-- 用户数据Table -->
      <el-table :data="tableData" stripe style="width: 100%" height="90%">
        <el-table-column prop="uid" label="ID"> </el-table-column>
        <el-table-column prop="uname" label="用户名"> </el-table-column>
        <!-- 改4 -->
        <el-table-column prop="uheadshot" label="头像">
          <template slot-scope="scope">
            <img
                :src="scope.row.uheadshot"
                alt="头像"
                style="width: 50px; height: 50px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="fans" label="粉丝数"> </el-table-column> -->
        <el-table-column prop="udelete" label="删除状态"> </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleReset(scope.row)" title="重置"
            >重置</el-button
            >
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                title="删除"
            >删除</el-button
            >
            <el-button
                size="mini"
                @click="handleRecover(scope.row)"
                title="恢复"
            >恢复</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pager">
        <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageData.limit"
            :current-page="pageData.page"
            @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import CommonForm from "@/components/manager/CommonForm.vue";
import CommonTable from "@/components/manager/CommonTable.vue";
export default {
  name: "user",
  components: {
    CommonForm,
    CommonTable,
  },
  data() {
    return {
      tableData: [],
      operateType: "add",
      isShow: false,
      token: null,
      opertateFormLabel: [
        {
          model: "uname",
          label: "用户名",
          type: "input",
        },
        {
          model: "upassword",
          label: "用户密码",
          type: "input",
        },
        {
          model: "uheadshot",
          label: "头像",
          type: "file",
          accept: "image/*",
        },
      ],
      operateForm: {
        uname: "",
        uid: "",
        uheadshot: "",
        fans: "",
        delete: "",
      },
      formLabel: [
        {
          model: "keyword",
          label: "",
          type: "input",
        },
      ],
      formLabel2: [
        {
          model: "keyword",
          label: "",
          type: "delete",
        },
      ],
      searchFrom1: {
        keyword: "",
      },
      searchFrom2: {
        keyword: "",
      },
      searchFrom3: {
        keyword: "",
      },
      pageData: {
        page: 1,
        limit: 5,
      },
      total: 0,
    };
  },
  methods: {
    //改8
    confirm() {
      const userData = {
        userName: this.operateForm.uname,
        userPassword: this.operateForm.upassword,
        userHeadshot: "https://azrael-first.oss-cn-shanghai.aliyuncs.com/1.jpg",
      };
      this.$http
          .post("/api/user/register", userData)
          .then((response) => {
            if (response.data.code === 20000) {
              this.$message.success("用户注册成功");
              this.isShow = false;
            } else {
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("注册失败：" + error.message);
          });
      this.getData();
    },
    addUser() {
      (this.isShow = true), (this.operateType = "add");
      this.operateForm = {
        name: "",
        password: "123456",
        headshot: "",
      };
    },
    // handleReset(index) {
    //   this.$emit("reset", row);
    // },
    // handleDelete(row) {
    //   this.$emit("del", row);
    // },
    // handleRecover(row) {
    //   this.$emit("recover", row);
    // },
    // currentChange(page) {
    //   this.$emit("changePage", page);
    // },
    getDelete() {
      const { page, limit } = this.pageData;
      const token = localStorage.getItem("token");
      const username = ""; // 获取用户名输入框的值，如果为空则设为空值
      const userdelete = this.searchFrom1.keyword[0] || "2"; // 获取删除状态输入框的值，如果为空则设为空值

      let url = `/api/user/select-name?username=${username}&userdelete=${userdelete}&page=${page}&pageSize=${limit}`;

      this.$http
          .get(url, { headers: { token: this.token } })
          .then((response) => {
            if (response.data.code === 20000) {
              this.tableData = response.data.data;
              this.total = response.data.data.total;
              this.getList();
            } else {
              if (response.data.code === 40100 && this.$route.path !== "/login") {
                this.$router.push("/login");
              }
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("获取数据失败：" + error.message);
          });
    },
    //用户名模糊查询
    getData() {
      // const data = {
      //   username: this.searchFrom2.keyword,
      //   userdelete: this.searchFrom1.keyword[0] || "2",
      //   page: this.pageData,
      //   pageSize :10
      // }
      const { page, limit } = this.pageData;
      const keyword = this.searchFrom2.keyword;
      //const lastChar = keyword.slice(-1);
      const userdelete = this.searchFrom1.keyword;

      let url = `/api/user/select-name?username=${keyword}&userdelete=${userdelete}&page=${page}&pageSize=${limit}`;

      this.$http
          .get(url, { headers: { token: this.token } })
          .then((response) => {
            if (response.data.code === 20000) {
              const fetchedData = response.data.data.rows;
              this.tableData = fetchedData;
              this.total = response.data.data.total;
              this.tableData = fetchedData.map((item) => ({
                ...item,
                udelete: item.udelete === 1 ? "正常" : "禁用",
              }));
            } else {
              if (response.data.code === 40100) {
                this.$router.push("/login");
              }
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("获取数据失败：" + error.message);
          });
    },
    //id精确查询
    getList() {
      const id = this.searchFrom3.keyword;
      //const token = localStorage.getItem("token");
      let url = `/api/user/select-uid`;
      if (id) {
        url += `?id=${id}`;
      }

      this.$http
          .get(url, { headers: { token: this.token } })
          .then((response) => {
            if (response.data.code === 20000) {
              let fetchedData = response.data.data;
              if (!Array.isArray(fetchedData)) {
                fetchedData = [fetchedData];
              }
              this.tableData = fetchedData;
              this.total = fetchedData.length;
              this.tableData = fetchedData.map((item) => ({
                ...item,
                udelete: item.udelete === 1 ? "正常" : "禁用",
              }));
            } else {
              if (response.data.code === 40100) {
                this.$router.push("/login");
              }
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("获取列表失败：" + error.message);
          });
    },
    // 重置密码
    handleReset(index) {
      this.$confirm("此操作将重置该用户的密码，是否继续？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //const token = localStorage.getItem("token");
        const uid = index.uid;
        this.$http
            .put(`/api/emp/reset-code/${uid}`, {},{
              headers: { token: this.token },
            })
            .then((response) => {
              if (response.data.code === 20000) {
                this.$message.success("重置用户密码成功");
                this.getData(); // 更新用户列表
              } else {
                if (response.data.code === 40100) {
                  this.$router.push("/login");
                }
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error("重置失败：" + error.message);
            });
      });
    },
    //删除用户操作
    handleDelete(index) {
      this.$confirm("此操作将删除该用户，是否继续？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //const token = localStorage.getItem("token");
        const uid = index.uid;
        this.$http
            .delete(`/api/emp/${uid}`, {
              headers: { token: this.token },
            })
            .then((response) => {
              if (response.data.code === 20000) {
                this.$message.success("删除用户成功");
                this.getData(); // 更新用户列表
              } else {
                if (response.data.code === 40100) {
                  this.$router.push("/login");
                }
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
      });
    },
    //改变页码操作
    currentChange(val) {
      this.pageData.page = val;
      this.getData();
    },
    //恢复用户操作
    handleRecover(index) {
      this.$confirm("此操作将恢复该用户，是否继续？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //const token = localStorage.getItem("token");
        const id = index.uid;
        let url = `/api/emp/recover`;
        if (id) {
          url += `?uid=${id}`;
        }
        let x = this.token;

        this.$http
            .put(url, {},{
              headers: { token: x },
            })
            .then((response) => {
              if (response.data.code === 20000) {
                this.$message.success("恢复用户成功");
                this.getData(); // 更新用户列表
              } else {
                if (response.data.code === 40100) {
                  this.$router.push("/login");
                }
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error("恢复失败：" + error.message);
            });
      });
    },
  },
  created() {
    this.token = localStorage.getItem("token");
    if (!this.token) {
      this.$router.push("/login");
    } else {
      this.getData();
    }
  },
  // mounted() {
  //   // this.getList();
  //   this.getData();
  // },
};
</script>
<style lang="less" scoped>
.manage {
  height: 100%;

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 90%;
    position: relative;

    .pager {
      position: absolute;
      right: 20px;
      bottom: 0;
    }
  }
}
</style>
